package com.eascs.web.p2p.action;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.common.util.StringUtil;
import com.eascs.p2p.common.entity.FileEntity;
import com.eascs.p2p.common.service.IFileService;
import com.eascs.p2p.common.vo.ModelResult;
import com.eascs.site.controller.BaseRestController;
import com.eascs.site.view.BaseRestResult;
import com.eascs.web.p2p.conf.FtpConfig;
import com.eascs.web.p2p.file.FileTypeConstants;
import com.eascs.web.p2p.utils.FtpNetUtils;
import com.eascs.web.p2p.utils.StringUtils;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;

@RestController
public class CommonRestController extends BaseRestController{
	
	
	@Reference
	IFileService iFileService;
	
	@Value("${web.upload.path}")
	private String uploadPath;
	
	@Value("${web.image.domain}")
	private String imageDomain;		//图片服务器域名
	/**request
	 * 附件上传  
	 * @param type 附件种类
	 * @param keyCode 业务code
	 * @return
	 */
	@RequestMapping(value = "/bid_file/upload/{type}")
	//public BaseRestResult<Render[]> fileUpload(@RequestParam(value = "file", required = false) MultipartFile file, @PathVariable("type") String type,String keyCode) {
	public BaseRestResult<String> fileUpload(@RequestParam(value = "file", required = false) MultipartFile file, @PathVariable("type") String type,String keyCode) {
			if(StringUtil.isNull(keyCode)){
				return BaseRestResult.warn("请先保存标的信息，再上传附件！");
			}
		    String extendName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1).toLowerCase();//后缀名
			String yearmonth = StringUtils.getFourBitYearMonth(new Date());
			String datepath = yearmonth.substring(0, 2) + "/" + yearmonth.substring(2, 4) + "/";
			String randomstr = Long.toString(System.currentTimeMillis()) + StringUtils.getRandomString(2);
			String relatedir = type + "/" + datepath;//路径
			String newfilename = randomstr + "." + extendName;//文件名称
			try {
				FtpNetUtils.uploadFile(FtpConfig.ftpConfigSetting().getHref(), Integer.valueOf(FtpConfig.ftpConfigSetting().getPort()), FtpConfig.ftpConfigSetting().getUsername(), FtpConfig.ftpConfigSetting().getPassword(), relatedir, newfilename, file.getInputStream());
			} catch (Exception e) {
				e.printStackTrace();
			} 
			ModelResult<String> model=new ModelResult<String>();
			if (type.equals(FileTypeConstants.FILE_BID_CONTRACT)||type.equals(FileTypeConstants.FILE_BID_CARD)) {
				FileEntity fileEntity=new FileEntity();
				fileEntity.setKeyCode(keyCode);//业务主键
				fileEntity.setUrlpath(relatedir);//上传路径
				fileEntity.setFileTypeCode(type);
				fileEntity.setFileTypeName(FileTypeConstants.getDatalistName(type));
				fileEntity.setOriginalName(newfilename);
				fileEntity.setExtendName(extendName);
				fileEntity.setCreatDate(new Date());
				User user=UserHolder.getUser();
				if(user!=null){
					
					fileEntity.setCreatOr(user.getCname());
				}
				model=iFileService.fileUpload(fileEntity);
			}
		return BaseRestResult.buildClosestReloadResult();//info("上传成功").andClosestReload("file_uploader");
				//BaseRestResult.render(new Render[] { new Render("#"+param, model.getModel()) });
				//BaseRestResult.buildClosestReloadResult();//info("上传成功").andClosestReload("file_uploader");
	}
	/**response
	 * 附件上传  
	 * @param fileId附件主键
	 * @return
	 */
	@RequestMapping(value = "/file/download")
	public void download(String fileId,HttpServletResponse httpServletResponse) {
		
		ModelResult<FileEntity> model =  iFileService.findFileById(fileId);
		FileEntity attachment=model.getModel();
		//扩展名和文件名
		String filename = attachment.getOriginalName();
		try {
			filename = URLEncoder.encode(filename,"UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		String extname = attachment.getExtendName();

		if ("bmp,jpeg,gif".indexOf(extname) != -1) {
			httpServletResponse.setContentType("image/"+extname);
		} else if ("jpg".equals(extname)) {
			httpServletResponse.setContentType("image/jpeg");
		} else if ("xls".equals(extname)) {
			httpServletResponse.setContentType("application/vnd.ms-excel");
			httpServletResponse.setHeader("Content-disposition", "attachment; filename="+filename);	
		} else if ("doc".equals(extname)) {
			httpServletResponse.setContentType("application/msword; charset=UTF-8");
			httpServletResponse.setHeader("Content-disposition", "attachment; filename="+filename);	
		} else if ("ppt".equals(extname)) {
			httpServletResponse.setContentType("application/vnd.ms-powerpoint; charset=UTF-8");
			httpServletResponse.setHeader("Content-disposition", "attachment; filename="+filename);	
		}else{
			httpServletResponse.setHeader("Content-disposition", "attachment; filename="+filename);	
		}

		//输出流
		try {
			boolean s = FtpNetUtils.downFile1(FtpConfig.ftpConfigSetting().getHref(), 
					Integer.valueOf(FtpConfig.ftpConfigSetting().getPort()), 
					FtpConfig.ftpConfigSetting().getUsername(), 
					FtpConfig.ftpConfigSetting().getPassword(), 
					attachment.getUrlpath().substring(0, attachment.getUrlpath().lastIndexOf("/")+1), 
					attachment.getUrlpath().substring(attachment.getUrlpath().lastIndexOf("/")+1, attachment.getUrlpath().length()), 
					httpServletResponse);
			if (!s) {
				ServletOutputStream outs = httpServletResponse.getOutputStream();
				httpServletResponse.setContentType("text/html;charset=UTF-8");
			    StringBuffer stringBuffer = new StringBuffer();
			    outs.print(new String(stringBuffer.toString().getBytes("UTF-8"),"utf-8"));
			    outs.flush();
				outs.close();
			}
		} catch (Exception e) {
			
		}

	}
	
	
	
	/**response
	 * 附件上传  
	 * @param fileId附件主键
	 * @return
	 */
	@RequestMapping(value = "/file/del")
	public BaseRestResult<String> delFile(String fileId) {
		 iFileService.delFile(fileId);
		 return  BaseRestResult.refresh();//
	}
	
	
	
	

}
